/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hxg
 */
public class pinyinUtils {

    private final static Logger logger = Logger.getLogger(pinyinUtils.class.getName());
    private final static LinkedHashMap<Character, String> mp = new LinkedHashMap(7000);

    static {
        load();
    }

    public static void load() {
        InputStreamReader isr=null;
        BufferedReader read = null;

        //PrintWriter pw=null;
        try {
            File f = new File("pinyin.txt");
            isr = new InputStreamReader(new FileInputStream(f), "UTF-8");
            read = new BufferedReader(isr);
            String s;
            while ((s = read.readLine()) != null) {
                if (s.length() > 2) {
                    mp.put(s.charAt(0), s.substring(2));
                }
            }
            logger.log(Level.INFO, "载入拼音{0}条", mp.size());
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, "没有找到文件[pinyin.txt]或文件读取异常");
        } finally {
            try {
                isr.close();
                read.close();
                //pw.flush();
                //pw.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
    }

    /*
    public static void load2() {
    BufferedReader read = null;
    try {
    File f = new File("pinyin.txt");
    read = new BufferedReader(new FileReader(f));
    String s;
    int i = 0;
    while ((s = read.readLine()) != null) {
    chs[i] = s.charAt(0);
    ss[i] = s.substring(2);
    i++;
    }
    } catch (IOException ex) {
    Logger.getLogger(pinyinUtils.class.getName()).log(Level.SEVERE, null, "没有找到文件[pinyin.txt]或文件读取异常");
    } finally {
    try {
    read.close();
    } catch (IOException ex) {
    Logger.getLogger(pinyinUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }
     */
    public static String getPinyinOfString(String str) {
        StringBuilder sb = new StringBuilder();
        for (char ch : str.toLowerCase().toCharArray()) {
            if (mp.containsKey(ch)) {
                sb.append(mp.get(ch));
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
    /*
    public static String getPinyinOfString2(String str) {
    StringBuilder sb = new StringBuilder();
    for (char ch : str.toLowerCase().toCharArray()) {
    if (ch > 128) {
    int idx = Arrays.binarySearch(chs, ch);
    if (idx >= 0) {
    sb.append(ss[idx]);
    } else {
    sb.append(ch);
    }
    } else {
    sb.append(ch);
    }
    }
    return sb.toString();
    }
     * */
}
